package com.cc.user.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cc.common.utils.PageUtils;
import com.cc.common.utils.R;
import com.cc.user.dao.DemandVoDao;
import com.cc.user.entity.DemandnotePictureEntity;
import com.cc.user.entity.UserEntity;
import com.cc.user.feign.MallFeign;
import com.cc.user.service.DemandnotePictureService;
import com.cc.user.service.UserService;
import com.cc.user.vo.DemandVo;
import com.cc.user.vo.DueVo;
import com.cc.user.vo.OfflineOrderEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cc.user.dao.DemandnoteDao;
import com.cc.user.entity.DemandnoteEntity;
import com.cc.user.service.DemandnoteService;
import org.springframework.util.StringUtils;


@Service("demandnoteService")
public class DemandnoteServiceImpl extends ServiceImpl<DemandnoteDao, DemandnoteEntity> implements DemandnoteService {

    @Autowired
    private UserService userService;

    @Autowired
    private MallFeign mallFeign;

    @Autowired
    private DemandnotePictureService demandnotePictureService;

    @Autowired
    private DemandVoDao demandVoDao;

    @Override
    public List<DemandnoteEntity> getAllDemandnote(Long id) {
        List<DemandnoteEntity> list = baseMapper.getAllDemandnote(id);
        for (DemandnoteEntity demandnoteEntity : list) {
            List<DemandnotePictureEntity> did = demandnotePictureService.list(new QueryWrapper<DemandnotePictureEntity>().eq("did", demandnoteEntity.getId()));
            demandnoteEntity.setDemandnotePictures(did.stream().map(m -> {
                return m.getDemandnotePicture();
            }).collect(Collectors.toList()));
        }
        return list;
    }

    @Override
    public Long toJK(Long ooid, String phone, String receiveMoney, List<String> pics) {
        DemandnoteEntity demandnoteEntity = new DemandnoteEntity();
        demandnoteEntity.setDemandnoteStatus(0);
        demandnoteEntity.setOoid(ooid);
        demandnoteEntity.setPayeeId(userService.getOne(new QueryWrapper<UserEntity>().eq("mobile",phone).eq("permission",1)).getUid());
        demandnoteEntity.setReceiveMoney(new BigDecimal(receiveMoney));
        demandnoteEntity.setCreatetime(new Date());
        baseMapper.insert(demandnoteEntity);
        List<DemandnotePictureEntity> demandnotePictureEntities = new ArrayList<>();
        for (String pic : pics) {
            DemandnotePictureEntity demandnotePictureEntity = new DemandnotePictureEntity();
            demandnotePictureEntity.setDid(demandnoteEntity.getId());
            demandnotePictureEntity.setDemandnotePicture(pic);
            demandnotePictureEntities.add(demandnotePictureEntity);
        }
        demandnotePictureService.saveBatch(demandnotePictureEntities);
        return demandnoteEntity.getId();
    }

    @Override
    public List<DueVo> getAllYJKById(Long id) {
        // List<DueVo> dueVo = baseMapper.getAllYJKById(id);
        R offlineOrderByCid = mallFeign.getOfflineOrderByCid(id);
        List<DueVo> dueVos = offlineOrderByCid.getData("list", new TypeReference<List<DueVo>>() {
        });
        // 过滤掉不需要显示的
        return dueVos.stream().filter(f -> f.getAmountsPayable().compareTo(f.getAmountsPaid()) > 0)
                .map(m -> {
                    m.setAmountsPayable(m.getAmountsPayable().subtract(m.getAmountsPaid()));
                    m.setYwyName(userService.getById(m.getEid()).getNickname());
                    return m;
                }).collect(Collectors.toList());
    }

    @Override
    public Page<DemandVo> getAllDemand(Map<String, Object> params) throws ParseException {
        String nickname = (String)params.get("nickname");
        String mobile = (String)params.get("mobile");
        String begin = (String) params.get("begin");
        String end = (String) params.get("end");
        int page = Integer.parseInt((String) params.get("page"));
        int limit = Integer.parseInt((String) params.get("limit"));
        Page<DemandVo> demandVoPage = new Page<>(page, limit);
        QueryWrapper<DemandVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("cd.createtime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(!StringUtils.isEmpty(begin)){
            begin = begin+" 00:00:00";
            queryWrapper.ge("cd.createtime",sdf.parse(begin));
        }
        if(!StringUtils.isEmpty(end)){
            end = end+" 23:59:00";
            queryWrapper.le("cd.createtime",sdf.parse(end));
        }
        if(!StringUtils.isEmpty(mobile)){
            nickname = userService.getOne(new QueryWrapper<UserEntity>().eq("mobile", mobile).eq("permission", 2)).getNickname();
        }
        if(!StringUtils.isEmpty(nickname))
            queryWrapper.eq("cu1.nickname",nickname);
        demandVoDao.selectDemandVoPage(demandVoPage,queryWrapper);
        List<DemandVo> records = demandVoPage.getRecords();
        records = records.stream().map(m1 -> {
            List<DemandnotePictureEntity> did = demandnotePictureService.list(new QueryWrapper<DemandnotePictureEntity>().eq("did", m1.getId()));
            m1.setDemandnotePictures(did.stream().map(m -> {
                return m.getDemandnotePicture();
            }).collect(Collectors.toList()));
            return m1;
        }).collect(Collectors.toList());
        demandVoPage.setRecords(records);
        return demandVoPage;
    }

    @Override
    public void shenhe(Long id, Long ooid,Integer type) {
        if(type == 1){
            // 1.改变缴款表的状态为1，审核通过
            DemandnoteEntity demandnoteEntity = baseMapper.selectById(id);
            demandnoteEntity.setDemandnoteStatus(1);
            baseMapper.updateById(demandnoteEntity);
            // 2.对线下订单的已付款字段
            DueVo dueVo = mallFeign.info(ooid).getData("offlineOrder", new TypeReference<DueVo>() {
            });
            // 获取已付款
            BigDecimal amountsPaid = dueVo.getAmountsPaid();
            amountsPaid = amountsPaid.add(demandnoteEntity.getReceiveMoney());
            OfflineOrderEntity offlineOrderEntity = new OfflineOrderEntity();
            offlineOrderEntity.setAmountsPaid(amountsPaid);
            offlineOrderEntity.setId(ooid);
            mallFeign.update(offlineOrderEntity); // 修改线下订单已付款价格
        }else {
            // 审核不通过
            DemandnoteEntity demandnoteEntity = baseMapper.selectById(id);
            demandnoteEntity.setDemandnoteStatus(2);
            baseMapper.updateById(demandnoteEntity);
        }
    }

    @Override
    public DueVo getYJKXQ(Long id) {
        DueVo yjkxq = baseMapper.getYJKXQ(id);
        yjkxq.setAmountsPayable(yjkxq.getAmountsPayable().subtract(yjkxq.getAmountsPaid()));
        return yjkxq;
    }
}